require 'java'

# Construct and return a new JRuby object from persistence
def activate_object(persistence_partner)
  puts "activate_object called!"
  o = Object.new
  begin
    o.instance_eval(persistence_partner.codebehind)
    storage = persistence_partner.getStorage()
    unless(storage.nil?)
      bis = java.io.ByteArrayInputStream.new(storage)
      instance_vars = Marshal.load(bis.to_io)
      instance_vars.each do |sym,value|
        o.instance_variable_set(sym, value)
      end
    end
    return o
  rescue => e
    puts e.inspect
    puts e.backtrace
    return e
  end
end

# Given a JRuby object, disassemble it and send it to the partner
def deactivate_object(persistence_partner, o)
  # Changing the codebehind for the object is beyond the scope of this method
  begin
    instance_vars = {}
    o.instance_variables.each do |var|
      instance_vars[var] = o.instance_variable_get(var)
    end
    baos = java.io.ByteArrayOutputStream.new
    io = baos.to_io
    Marshal.dump(instance_vars, io)
    persistence_partner.setStorage(baos.toByteArray())
  rescue => e
    puts e.inspect
    puts e.backtrace
    return e
  end
end